import { localsKeys } from '../../locals';
import { i18n } from '../../common/i18n';
import { devLog } from '../../utils/dev-log';
import { IResponse } from './types';

export const transformResponse = <T = any>(res: IResponse<T>): T => {
  if (res?.status === 'OK') {
    return res?.data;
  }

  const hasStatus = localsKeys.includes(`error-${res?.status}`);

  const errorMessage = i18n.t(`error-${res?.status}` as any, {
    message: res?.error_message || 'Unknown Error!',
  });

  const networkErrorMessage = i18n.t('error-error', {
    message: res?.error_message || 'Network Error!',
  });

  const message = hasStatus ? errorMessage : networkErrorMessage;

  devLog('[error - message]', res, message);

  throw {
    message,
  };
};
